package ordersubmit

import (
	// "fmt"

	"mall/common/globalkey"
	"mall/service/product/rpc/productclient"
	// "github.com/sirupsen/logrus"
	// "github.com/zeromicro/go-zero/core/logx"
)

// StockSubtractHandler 商品库存操作handler
type StockSubtractHandler struct {
	// 合成复用Next
	Next
}

// Do 扣库存
func (h *StockSubtractHandler) Do(c *Context) (err error) {
	if !c.Resp.StockValid || !c.Resp.AddressValid || !c.Resp.PromotionValid ||
		!c.Resp.ActivityValid || !c.Resp.CouponValid || !c.Resp.FinalValid {
		return
	}

	if c.OrderType == globalkey.OrderTypeVirtual {
		return
	}

	// logx.Infow("扣库存...")

	// 2.1. 普通实物 冻结库存
	var stocks []*productclient.ProductVariationStock
	skuIdQtyMap := make(map[uint64]uint32)
	for _, v := range c.Req.Skus {
		if v.SkuId != nil && v.Quantity != nil && *v.SkuId > 0 && *v.Quantity > 0 {
			if num, ok := skuIdQtyMap[*v.SkuId]; !ok {
				skuIdQtyMap[*v.SkuId] = *v.Quantity
			} else {
				skuIdQtyMap[*v.SkuId] = num + *v.Quantity
			}
		}
	}
	for skuId, qty := range skuIdQtyMap {
		stocks = append(stocks, &productclient.ProductVariationStock{
			Id:    skuId,
			Stock: qty,
		})
	}
	_, err = c.SvcCtx.ProductRpc.CheckAndSubtractStock(c.Ctx, &productclient.CheckAndSubtractStockReq{
		// res, err := c.SvcCtx.ProductRpc.CheckAndSubtractStock(c.Ctx, &productclient.CheckAndSubtractStockReq{
		Data: stocks,
	})
	if err != nil {
		return err
	}

	c.Stocks = stocks

	// logrus.Info(fmt.Sprintf("StockSubtractHandler: %+v", res))

	return
}
